package com.seafood.controller;

import com.seafood.common.Result;
import com.seafood.dto.LoginResponseDTO;
import com.seafood.dto.UserDTO;
import com.seafood.dto.UserLoginDTO;
import com.seafood.dto.UserRegisterDTO;
import com.seafood.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@Tag(name = "认证管理", description = "用户认证相关API")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {
    
    private final UserService userService;
    
    /**
     * 用户注册
     */
    @Operation(summary = "用户注册", description = "新用户注册接口")
    @PostMapping("/register")
    public Result<UserDTO> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        try {
            UserDTO userDTO = userService.register(registerDTO);
            return Result.success("注册成功", userDTO);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户登录接口，返回JWT token")
    @PostMapping("/login")
    public Result<LoginResponseDTO> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        try {
            LoginResponseDTO response = userService.login(loginDTO);
            return Result.success("登录成功", response);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @Operation(summary = "获取用户信息", description = "获取当前登录用户的详细信息")
    @GetMapping("/profile")
    public Result<UserDTO> getProfile(Authentication authentication) {
        try {
            String username = authentication.getName();
            UserDTO userDTO = userService.convertToDTO(userService.findByUsername(username));
            return Result.success(userDTO);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @Operation(summary = "更新用户信息", description = "更新当前登录用户的信息")
    @PutMapping("/profile")
    public Result<UserDTO> updateProfile(@Valid @RequestBody UserDTO userDTO, 
                                        Authentication authentication) {
        try {
            String username = authentication.getName();
            var currentUser = userService.findByUsername(username);
            UserDTO updatedUser = userService.updateUser(currentUser.getId(), userDTO);
            return Result.success("更新成功", updatedUser);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @Operation(summary = "用户登出", description = "用户登出接口")
    @PostMapping("/logout")
    public Result<Void> logout() {
        // JWT是无状态的，登出主要由前端处理（删除本地存储的token）
        // 这里可以实现token黑名单机制（可选）
        return Result.success("登出成功", null);
    }
    
    /**
     * 检查用户名是否可用
     */
    @Operation(summary = "检查用户名", description = "检查用户名是否已被注册")
    @GetMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        boolean exists = userService.existsByUsername(username);
        return Result.success(!exists); // 返回true表示可用，false表示已存在
    }
    
    /**
     * 检查邮箱是否可用
     */
    @Operation(summary = "检查邮箱", description = "检查邮箱是否已被注册")
    @GetMapping("/check-email")
    public Result<Boolean> checkEmail(@RequestParam String email) {
        boolean exists = userService.existsByEmail(email);
        return Result.success(!exists); // 返回true表示可用，false表示已存在
    }
}